/**
 * @file ext-primitive-lib.js
 *
 * @license MIT
 *
 * @copyright 2010 Christian Tzurcanu, 2010 Alexis Deveria
 *
 */
const name = 'graphicEditing'
const defsIdMap = new Map();
const loadExtensionTranslation = async function (svgEditor) {
  let translationModule
  const lang = svgEditor.configObj.pref('lang')
  try {
    translationModule = await import(`./locale/${lang}.js`)
  } catch (_error) {
    console.warn(`Missing translation (${lang}) for ${name} - using 'en'`)
    translationModule = await import('./locale/en.js')
  }
  svgEditor.i18next.addResourceBundle(lang, name, translationModule.default)
}


const updateLib = async  function () {
  try {
    const response = await fetch(`${svgEditor.configObj.curConfig.serviceUrl}/svg/graphics/list`)
    const  data = (await response.json()).data;
    let  template = document.createElement('template');
    for(let i in data){
       var obj = data[i];
       if(!obj.length) continue;
       for(let j=0;j<obj.length;j++){
        if(j>=1) continue;
        let title = obj[j].title;
        let content = obj[j].content;
        let id = obj[j].id;
        let encoded = btoa(unescape(encodeURIComponent(content)))
        template.innerHTML += `<se-button  id="${title}"   title="${title}" src="data:image/svg+xml;base64,${encoded}"></se-button>`
       }
       
       $('#tools_left .shaps .itemWrap').append(template.content.cloneNode(true))
    







   
      
    }
  

  } catch (error) {
    console.error(`could not read files:${lib}`, error)
  }
 }

export default {
  name,
  async init () {
    const svgEditor = this
    const svgCanvas = svgEditor.svgCanvas
    const { $id, $click ,$qq, $ } = svgCanvas
    const svgroot = svgCanvas.getSvgRoot()
    let lastBBox = {}
    await loadExtensionTranslation(svgEditor)
    await updateLib();
    const modeId = 'primitivelib'
    const startClientPos = {}

    let curShape,defs
    let startX
    let startY

    return {
      callback () {
        // if ($id('tool_primitivelib') === null) {
        //   const buttonTemplate = `
        //   <se-primitiveexplorerbutton id="tool_primitivelib" title="${svgEditor.i18next.t(`${name}:buttons.0.title`)}" lib="${new Date().getTime()}"
        //   src="shapelib.svg"></se-primitiveexplorerbutton>
        //   `
        //   svgCanvas.insertChildAtIndex($qq ('.basicWrap .itemWrap'), buttonTemplate, 12)
        //   $click($id('tool_primitivelib'), () => {
        //     if (this.leftPanel.updateLeftPanel('tool_primitivelib')) {
        //       svgCanvas.setMode(modeId)
        //     }
        //   })
        // }
     
    
      },
      mouseDown (opts) {
        const mode = svgCanvas.getMode()
        if (mode !== modeId) { return undefined }

        const curContent = $id('tool_primitivelib').dataset.draw
        const curType = $id('tool_primitivelib').dataset.docType
        const curStyle = svgCanvas.getStyle()

        const addElement = (curShape, element) => {
          let children = $(element).children().length > 0 ? $(element).children() : element
          Array.from(children).forEach((elem, i) => {
            let tagName = elem.tagName;

            if (tagName == 'g') {
              let childShape = svgCanvas.addSVGElementsFromJson({
                element: 'g',
                attr: {
                  id: svgCanvas.getNextId(),
                  opacity: 1,
                  state: i
                }
              });

              let children = $(elem).children()
              if (children.length > 0) {
                // 删除父节点状态字
                curShape.removeAttribute('state')
              }
              $(curShape).append(childShape);
              addElement(childShape , children);
            } else {
              if(tagName == 'title' || tagName == 'defs') {
                return
              }
              let newElement = $(elem).clone().attr({
                id: svgCanvas.getNextId(),
                'stroke-width': 1
              });

              let fillAttr = $(elem).attr('fill')
              let strokeAttr = $(elem).attr('stroke')

              const fillAttrId = _.trimEnd(_.trimStart(fillAttr, 'url(#'), ')')
              const strokeAttrId = _.trimEnd(_.trimStart(strokeAttr, 'url(#'), ')')
              if (defsIdMap.has(fillAttrId)) {
                $(newElement).attr('fill', `url(#${defsIdMap.get(fillAttrId)})`)
              }

              if (defsIdMap.has(strokeAttrId)) {
                $(newElement).attr('stroke', `url(#${defsIdMap.get(strokeAttrId)})`)
              }

              $(curShape).append(newElement);
              if (tagName == "path") {
                let path = newElement[0]
                const d = newElement.attr("d");
                if (/[a-z]/.test(d)) {
                  const convertedPath = svgCanvas.pathActions.convertPath(path);
                  path.setAttribute('d', convertedPath);
                  svgCanvas.pathActions.fixEnd(path);
                }
                svgCanvas.recalculateDimensions(path);
              }
            }
          });
        };

        let elements = $(curContent).find("g>*")
        defs = $(curContent).find("defs>*")

        if (defs.length > 0) {
          Array.from(defs).forEach((elem, i) => {
            const oldId = elem.id
            const newId = svgCanvas.getNextId()
            
            var def_ = svgCanvas.findDuplicateGradient(elem)
            if(def_ == null){
              defsIdMap.set(oldId, newId)
              elem.setAttribute('id', newId)
              svgCanvas.findDefs().append(elem)
            }
          })
        }

        if (elements.length > 0) {
          curShape = svgCanvas.addSVGElementsFromJson({
            element: 'g',
            curStyles: true,
            attr: {
              id: svgCanvas.getNextId(),
              'docType': curType,
              opacity: curStyle.opacity / 2,
              class: 'ems'
            }
          });
          addElement(curShape, curContent);
        } else {
          return
        }

        startX = opts.start_x
        const x = startX
        startY = opts.start_y
        const y = startY

        startClientPos.x = opts.event.clientX
        startClientPos.y = opts.event.clientY

        curShape.setAttribute('transform', 'translate(' + x + ',' + y + ') scale(0.005) translate(' + -x + ',' + -y + ')')

        svgCanvas.recalculateDimensions(curShape)

        lastBBox = curShape.getBBox()

        return {
          started: true
        }
      },
      mouseMove (opts) {
        const mode = svgCanvas.getMode()
        if (mode !== modeId) { return }

        const zoom = svgCanvas.getZoom()
        const evt = opts.event

        const x = opts.mouse_x / zoom
        const y = opts.mouse_y / zoom

        const tlist = curShape.transform.baseVal
        const box = curShape.getBBox()
        const left = box.x; const top = box.y

        const newbox = {
          x: Math.min(startX, x),
          y: Math.min(startY, y),
          width: Math.abs(x - startX),
          height: Math.abs(y - startY)
        }

        let sx = (newbox.width / lastBBox.width) || 1
        let sy = (newbox.height / lastBBox.height) || 1

        // Not perfect, but mostly works...
        let tx = 0
        if (x < startX) {
          tx = lastBBox.width
        }
        let ty = 0
        if (y < startY) {
          ty = lastBBox.height
        }

        // update the transform list with translate,scale,translate
        const translateOrigin = svgroot.createSVGTransform()
        const scale = svgroot.createSVGTransform()
        const translateBack = svgroot.createSVGTransform()

        translateOrigin.setTranslate(-(left + tx), -(top + ty))
        if (!evt.shiftKey) {
          const max = Math.min(Math.abs(sx), Math.abs(sy))

          sx = max * (sx < 0 ? -1 : 1)
          sy = max * (sy < 0 ? -1 : 1)
        }
        scale.setScale(sx, sy)

        translateBack.setTranslate(left + tx, top + ty)
        tlist.appendItem(translateBack)
        tlist.appendItem(scale)
        tlist.appendItem(translateOrigin)

        svgCanvas.recalculateDimensions(curShape)

        lastBBox = curShape.getBBox()
      },
      mouseUp (opts) {
        const mode = svgCanvas.getMode()
        if (mode !== modeId) { return undefined }

        const keepObject = (opts.event.clientX !== startClientPos.x && opts.event.clientY !== startClientPos.y)

        svgCanvas.setMode('select')

        return {
          keep: keepObject,
          element: curShape,
          started: false
        }
      },
      

    }
  }
}
